package com.mega.ebcs.anttask;

import org.apache.commons.lang.StringUtils;

public class DMLConverter {

	protected String[] columnName;
	protected String[] columnValue;
	protected String tableName;
	
	public String[] getColumnName() {
		return columnName;
	}
	public void setColumnName(String[] columnName) {
		this.columnName = columnName;
	}
	public String[] getColumnValue() {
		return columnValue;
	}

	public void setColumnValue(String[] columnValue) {
		this.columnValue = columnValue;
	}

	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	
	public DMLConverter(String tableName, String[] columnName, String[] columnValue) {
		this.tableName = tableName;
		this.columnName = columnName;
		
		for(int i=0; i<columnValue.length; i++) {
			columnValue[i] = escapeColumnValue(columnName[i], columnValue[i]);
		}
		this.columnValue = columnValue;
	}
	
	protected String escapeColumnValue(String column, String value) {
		if(StringUtils.isEmpty(value)) return "NULL";
		
		// bit column
		if(StringUtils.equalsIgnoreCase("status", column)) return value;
		if(StringUtils.equalsIgnoreCase("enabled", column)) return value;
		
		value = value.replaceAll("[']", "''");
		//value = value.replaceAll("[&]", "' + char(38) +'");
		value = value.replaceAll("[\t]", "' + char(9) +'");
		value = value.replaceAll("[\n]", "' + char(13) +'");
		
		return "'"+value+"'";
	}
	
	public String toString() {
		
		String strColumn = StringUtils.join(columnName, ",");
		String strValue = StringUtils.join(columnValue, ",");
		
		return "INSERT INTO "+tableName+"("+strColumn+") values ("+strValue+");\r\n";
	}
}
